package com.jucai.pppeiyouclient.view.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.Selection;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jucai.pppeiyouclient.MainActivity;
import com.jucai.pppeiyouclient.R;
import com.jucai.pppeiyouclient.adapter.SamplePagerAdapter;
import com.jucai.pppeiyouclient.base.BaseTakePhotoActivity;
import com.jucai.pppeiyouclient.base.PermissionListener;
import com.jucai.pppeiyouclient.bean.AccompanyBean;
import com.jucai.pppeiyouclient.bean.PersonalPhotoBean;
import com.jucai.pppeiyouclient.comm.CommonData;
import com.jucai.pppeiyouclient.comm.CommonMethod;
import com.jucai.pppeiyouclient.comm.CommonRequestNetData;
import com.jucai.pppeiyouclient.utils.ActivityCollector;
import com.jucai.pppeiyouclient.utils.CompressPhoto;
import com.jucai.pppeiyouclient.utils.ImageHandleUtils;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.OssUtils;
import com.jucai.pppeiyouclient.utils.ToastUtils;
import com.jucai.pppeiyouclient.view.dialog.FullScreenDialog;
import com.jucai.pppeiyouclient.view.popup.EduChoosePopup;
import com.jucai.pppeiyouclient.view.popup.HeadUploadPopup;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

import static com.jucai.pppeiyouclient.R.id.person_age;

public class PersonalSettingsActivity extends BaseTakePhotoActivity implements Handler.Callback{
    private static final String TAG = "PersonalSettingsActivity : ";
    private static final int TAKE_PHOTO = 2001;
    private static final int CHOOSE_IMAGE = 2002;
    private static final int CROP_IMAGE = 2003;
    private static final int TAKE_PHOTO_PERSONAL = 2004;
    private static final int TAKE_PHOTO_UPDATE1 = 2005;
    private static final int TAKE_PHOTO_UPDATE2 = 2006;
    private static final int TAKE_PHOTO_UPDATE3 = 2007;
    private static final int TAKE_PHOTO_UPDATE4 = 2008;

    private CircleImageView personImage;
    private TextView personNick, personAddSkill, personSkills, personEdu, personSave;
    private EditText personIntro, personAge, personCareer;
    private EduChoosePopup eduChoosePopup;
    private AccompanyBean accompany;
    private HeadUploadPopup headUploadPopup;
    private File imageStore = new File(Environment.getExternalStorageDirectory(),
            CommonData.STORAGE_PICTURE_HEAD_FILE + System.currentTimeMillis() + ".jpg");
    private String objectKey, personEduCode = "1";//保存头像路径
    private boolean isImageUploading = false;
    private List<String> imageListPath = new ArrayList<String>();
    private ImageView addImageUpload;
    private int curSelectUploadState;
    private static final int NONE = 0;//未选中
    private static final int HARDER = 1;//头像上传
    private static final int PHOTO = 2;//个人相册上传
    private Map<String, String> mapPhoto;
    private Handler handler;
    private ImageView initiate_show_img1, initiate_show_img2, initiate_show_img3, initiate_show_img4;
    private String objectPhoto;
    private String[] photPath;
    private PersonalPhotoBean personalBean;
    private List<PersonalPhotoBean> listBean = new ArrayList<PersonalPhotoBean>();
    private String imageKey = "";

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_personal_settings);

        ((TextView) findViewById(R.id.common_title_text)).setText("个人设置");
        personImage = (CircleImageView) findViewById(R.id.person_image);
        personNick = (TextView) findViewById(R.id.person_nick);
        personAddSkill = (TextView) findViewById(R.id.person_add_skill);
        personSkills = (TextView) findViewById(R.id.person_skills);
        personAge = (EditText) findViewById(person_age);
        personCareer = (EditText) findViewById(R.id.person_career);
        personEdu = (TextView) findViewById(R.id.person_edu);
        personSave = (TextView) findViewById(R.id.person_save);
        personIntro = (EditText) findViewById(R.id.person_intro);

        addImageUpload = (ImageView)this.findViewById(R.id.initiate_upload_img);
        initiate_show_img1 = (ImageView) findViewById(R.id.initiate_show_img1);
        initiate_show_img2 = (ImageView) findViewById(R.id.initiate_show_img2);
        initiate_show_img3 = (ImageView) findViewById(R.id.initiate_show_img3);
        initiate_show_img4 = (ImageView) findViewById(R.id.initiate_show_img4);

        initiate_show_img1.setVisibility(View.GONE);
        initiate_show_img2.setVisibility(View.GONE);
        initiate_show_img3.setVisibility(View.GONE);
        initiate_show_img4.setVisibility(View.GONE);

        photPath = new String[4];
        personalBean = new PersonalPhotoBean();
    }

    @Override
    protected void configCompress(TakePhoto takePhoto) {
        int maxSize = 1 * 1024 * 1024;
        int width;
        int height;
        if(curSelectUploadState == HARDER){
            width = 150;
            height = 150;
        }else{
            width = 800;
            height = 800;
        }
        boolean showProgressBar = true;
        boolean enableRawFile = true;//保留原图
        CompressConfig config = new CompressConfig.Builder()
                .setMaxSize(maxSize)
                .setMaxPixel(width >= height ? width : height)
                .enableReserveRaw(enableRawFile)
                .create();
        takePhoto.onEnableCompress(config, showProgressBar);
    }

    @Override
    protected void initData() {
        mapPhoto = new HashMap<>();
        handler = new Handler(this);
        personEdu.setText("不限");
        personEduCode = "0";

        eduChoosePopup = new EduChoosePopup(PersonalSettingsActivity.this, getWindow(), R.style.animBottomInBottomOut, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                eduChoosePopup.dismiss();
                switch (view.getId()) {
                    case R.id.edu_doctor:
                        personEdu.setText("博士");
                        personEduCode = "6";
                        break;
                    case R.id.edu_master:
                        personEdu.setText("硕士");
                        personEduCode = "5";
                        break;
                    case R.id.edu_undergraduate:
                        personEdu.setText("本科");
                        personEduCode = "4";
                        break;
                    case R.id.edu_junior:
                        personEdu.setText("专科");
                        personEduCode = "3";
                        break;
                    case R.id.edu_high_school:
                        personEdu.setText("高中");
                        personEduCode = "2";
                        break;
                    case R.id.edu_middle_school:
                        personEdu.setText("初中");
                        personEduCode = "1";
                        break;
                    case R.id.edu_other:
                        personEdu.setText("不限");
                        personEduCode = "0";
                        break;
                    default:
                        break;
                }
            }
        });

        headUploadPopup = new HeadUploadPopup(this, getWindow(), R.style.animBottomInBottomOut,
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        headUploadPopup.dismiss();
                        switch (view.getId()) {
                            case R.id.upload_photo:

                                if (Build.VERSION.SDK_INT >= 23) {
                                    PersonalSettingsActivity.this.onRuntimePermissionRequest(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                                            new PermissionListener() {
                                                @Override
                                                public void onGranted() {
                                                    if(curSelectUploadState == HARDER){
                                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO);
                                                    }else if(curSelectUploadState == PHOTO){
                                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_PERSONAL);
                                                    }else if(curSelectUploadState == 101){
                                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_UPDATE1);
                                                    }else if(curSelectUploadState == 102){
                                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_UPDATE2);
                                                    }else if(curSelectUploadState == 103){
                                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_UPDATE3);
                                                    }else if(curSelectUploadState == 104){
                                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_UPDATE4);
                                                    }
                                                }

                                                @Override
                                                public void onDenied(List<String> deniedPermissions) {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            ToastUtils.showToast("调起摄像头失败！");
                                                        }
                                                    });
                                                }
                                            });
                                } else{
                                    if(curSelectUploadState == HARDER){
                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO);
                                    }else if(curSelectUploadState == PHOTO){
                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_PERSONAL);
                                    }else if(curSelectUploadState == 101){
                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_UPDATE1);
                                    }else if(curSelectUploadState == 102){
                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_UPDATE2);
                                    }else if(curSelectUploadState == 103){
                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_UPDATE3);
                                    }else if(curSelectUploadState == 104){
                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_UPDATE4);
                                    }
                                }
                                break;
                            case R.id.upload_album:
                                if(curSelectUploadState == PHOTO){
                                    if (listBean.size() >= 4) {
                                        ToastUtils.showToast("最多选择4张");
                                        break;
                                    }
                                    if (isImageUploading) {
                                        ToastUtils.showToast("上传图片中，请稍后再试");
                                        break;
                                    }
                                    getTakePhoto().onPickMultiple(4 - listBean.size());
                                }else if(curSelectUploadState == HARDER){
                                    getTakePhoto().onPickMultiple(1);
                                }
//                                if (Build.VERSION.SDK_INT >= 23) {
//                                    //写SD卡权限申请
//                                    BaseActivity.onRuntimePermissionRequest(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                                            new PermissionListener() {
//                                                @Override
//                                                public void onGranted() {
//                                                    ImageHandleUtils.openAlum(PersonalSettingsActivity.this, CHOOSE_IMAGE);
//                                                }
//
//                                                @Override
//                                                public void onDenied(List<String> deniedPermissions) {
//                                                    for (String p : deniedPermissions) {
//                                                        Toast.makeText(ActivityCollector.getTopActivity(),
//                                                                p + "权限被拒绝", Toast.LENGTH_SHORT).show();
//                                                    }
//                                                }
//                                            });
//                                } else
//                                    ImageHandleUtils.openAlum(PersonalSettingsActivity.this, CHOOSE_IMAGE);
                                break;

                            case R.id.upload_cancel:
                                headUploadPopup.dismiss();
                                break;
                            default:
                                break;
                        }
                    }
                });

        getPersonInfo();

        LogUtils.e("listbean size = " + listBean.size());
        if (listBean.size() >= 4) {
            addImageUpload.setVisibility(View.GONE);
        }else{
            addImageUpload.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void loadNetData() {

    }

    private void getPersonInfo() {
        HashMap<String, String> param = new HashMap<>();
        param.put("service", "Accompany_Info.getAccompanyInfo");
        CommonRequestNetData.getJsonObjectData(PersonalSettingsActivity.this, param, true, new CommonRequestNetData.JsonObjectCallBack() {
            @Override
            public void parseJsonObject(JSONObject jsonObject) {
                LogUtils.e(TAG + "jsObj = " + jsonObject.toString());
                accompany = new Gson().fromJson(jsonObject.toString(), AccompanyBean.class);
                LogUtils.e(TAG + "accompany = " + accompany);
                imageKey = accompany.getMember_avatar();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(PersonalSettingsActivity.this)
                                .load(accompany.getMember_avatar())
                                .override(80, 80)
                                .centerCrop()
                                .into(personImage);

                        List<String> listPhoto = accompany.getAccompany_photo_list_arr();
                        LogUtils.e("listPhoto = " + listPhoto.toString());

                        if(!listPhoto.isEmpty()){
                            String[] arrayPhoto = null;
                            if(!TextUtils.isEmpty(accompany.getMember_photo())){
                                arrayPhoto = accompany.getMember_photo().split(",");
                                if(arrayPhoto.length > 0){
                                    for(int i = 0;i<arrayPhoto.length;i++){
                                        mapPhoto.put(arrayPhoto[i], listPhoto.get(i));
                                    }
                                }
                            }
                            for(int i=0;i<listPhoto.size();i++){
                                PersonalPhotoBean bean = new PersonalPhotoBean();
                                bean.photo_add_or_update = 0;
                                bean.view_photo_path = listPhoto.get(i);
                                if(i == 0){
                                    Glide.with(PersonalSettingsActivity.this)
                                            .load(listPhoto.get(0))
                                            .override(80, 80)
                                            .centerCrop()
                                            .into(initiate_show_img1);
                                    initiate_show_img1.setVisibility(View.VISIBLE);
                                    bean.view_id = "initiate_show_img1";
                                    if(arrayPhoto.length > 0){
                                        bean.member_phot = arrayPhoto[0];
                                    }
                                }else if(i == 1){
                                    Glide.with(PersonalSettingsActivity.this)
                                            .load(listPhoto.get(1))
                                            .override(80, 80)
                                            .centerCrop()
                                            .into(initiate_show_img2);
                                    bean.view_id = "initiate_show_img2";
                                    if(arrayPhoto.length > 1){
                                        bean.member_phot = arrayPhoto[1];
                                    }
                                    initiate_show_img2.setVisibility(View.VISIBLE);
                                }else if(i == 2){
                                    Glide.with(PersonalSettingsActivity.this)
                                            .load(listPhoto.get(2))
                                            .override(80, 80)
                                            .centerCrop()
                                            .into(initiate_show_img3);
                                    bean.view_id = "initiate_show_img3";
                                    if(arrayPhoto.length > 2){
                                        bean.member_phot = arrayPhoto[2];
                                    }
                                    initiate_show_img3.setVisibility(View.VISIBLE);
                                }else if(i == 3){
                                    Glide.with(PersonalSettingsActivity.this)
                                            .load(listPhoto.get(3))
                                            .override(80, 80)
                                            .centerCrop()
                                            .into(initiate_show_img4);
                                    bean.view_id = "initiate_show_img4";
                                    if(arrayPhoto.length > 3){
                                        bean.member_phot = arrayPhoto[3];
                                    }
                                    initiate_show_img4.setVisibility(View.VISIBLE);
                                }
                                listBean.add(bean);
                            }
                        }
                        if (listBean.size() >= 4) {
                            addImageUpload.setVisibility(View.GONE);
                        }else{
                            addImageUpload.setVisibility(View.VISIBLE);
                        }
                        personNick.setText(accompany.getMember_realname());
                        personAge.setText(accompany.getMember_age());
                        personCareer.setText(accompany.getMember_occupation());
                        switch (accompany.getMember_education()) {
                            case "6":
                                personEdu.setText("博士");
                                break;
                            case "5":
                                personEdu.setText("硕士");
                                break;
                            case "4":
                                personEdu.setText("本科");
                                break;
                            case "3":
                                personEdu.setText("专科");
                                break;
                            case "2":
                                personEdu.setText("高中");
                                break;
                            case "1":
                                personEdu.setText("初中");
                                break;
                            case "0":
                                personEdu.setText("不限");
                                break;
                            default:
                                break;
                        }
                        //personEdu.setText(accompany.getMember_education());
                        personIntro.setText(accompany.getMember_desc());
                        Selection.setSelection(personAge.getText(), personAge.getText().length());
                    }
                });
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TAKE_PHOTO:
                case TAKE_PHOTO_PERSONAL:
                case TAKE_PHOTO_UPDATE1:
                case TAKE_PHOTO_UPDATE2:
                case TAKE_PHOTO_UPDATE3:
                case TAKE_PHOTO_UPDATE4:
                    showCropImage(data,requestCode);
                    break;



//                case CHOOSE_IMAGE:
//                    ImageHandleUtils.startCropImage(PersonalSettingsActivity.this,
//                            data.getData(), CROP_IMAGE, 1, 1, 200, 200);
//                    break;
//                case CROP_IMAGE:
//                    if (data != null) {
//                        LogUtils.e(TAG + "after crop");
//                        showCropImage(data);
//                    }
//                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        for (TImage tImage : result.getImages())
            uploadImage(tImage);
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }


    private void uploadImage(TImage images) {
        try {
            String photoPath = images.getCompressPath();
            if (TextUtils.isEmpty(photoPath))
                photoPath = images.getOriginalPath();
            String tem;
            if(curSelectUploadState == HARDER){
                objectKey = "temp/" + System.currentTimeMillis() + ".jpg";
                tem = objectKey;
            }else{
                objectPhoto  = "temp/" + System.currentTimeMillis() + ".jpg";
                tem = objectPhoto;
            }
            final String pathTemp = photoPath;


            OssUtils.uploadPic(photoPath, tem, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {
                    isImageUploading = false;
                }

                @Override
                public void onFailure(PutObjectRequest putObjectRequest, ClientException e, ServiceException e1) {
                    isImageUploading = false;
                    if(curSelectUploadState == HARDER){
                        objectKey = "";
                    }else{
                        objectPhoto = "";
                    }
                    ToastUtils.showToast("头像上传失败！请稍后再试");
                }
            },new OssUtils.onPhotoUploadResult(){
                @Override
                public void onResult(String key, String filePath) {
                    if(curSelectUploadState == PHOTO){
                        mapPhoto.put(key, filePath);
                        PersonalPhotoBean bean = new PersonalPhotoBean();
                        bean.photo_add_or_update = 1;
                        bean.view_photo_path = pathTemp;
                        if(listBean.size() >= 4){
                            return;
                        }
                        if(listBean.size() == 0){
                            bean.view_id = "initiate_show_img1";
                        }else if(listBean.size() == 1){
                            bean.view_id = "initiate_show_img2";
                        }else if(listBean.size() == 2){
                            bean.view_id = "initiate_show_img3";
                        }else if(listBean.size() == 3){
                            bean.view_id = "initiate_show_img4";
                        }
                        bean.member_phot = key;
                        listBean.add(bean);
                        handler.sendEmptyMessage(1);
                    }else if(curSelectUploadState == 101){
                        mapPhoto.put(key, filePath);
                        PersonalPhotoBean bean = new PersonalPhotoBean();
                        bean.photo_add_or_update = 1;
                        bean.view_photo_path = pathTemp;
                        bean.view_id = "initiate_show_img1";
                        bean.member_phot = key;
                        listBean.set(0,bean);
                        handler.sendEmptyMessage(1);
                    }if(curSelectUploadState == 102){
                        mapPhoto.put(key, filePath);
                        PersonalPhotoBean bean = new PersonalPhotoBean();
                        bean.photo_add_or_update = 1;
                        bean.view_photo_path = pathTemp;
                        bean.view_id = "initiate_show_img2";
                        bean.member_phot = key;
                        listBean.set(1,bean);
                        handler.sendEmptyMessage(1);
                    }if(curSelectUploadState == 103){
                        mapPhoto.put(key, filePath);
                        PersonalPhotoBean bean = new PersonalPhotoBean();
                        bean.photo_add_or_update = 1;
                        bean.view_photo_path = pathTemp;
                        bean.view_id = "initiate_show_img3";
                        bean.member_phot = key;
                        listBean.set(2,bean);
                        handler.sendEmptyMessage(1);
                    }if(curSelectUploadState == 104){
                        mapPhoto.put(key, filePath);
                        PersonalPhotoBean bean = new PersonalPhotoBean();
                        bean.photo_add_or_update = 1;
                        bean.view_photo_path = pathTemp;
                        bean.view_id = "initiate_show_img4";
                        bean.member_phot = key;
                        listBean.set(3,bean);
                        handler.sendEmptyMessage(1);
                    }
                }

                @Override
                public void onProgress(long currentSize, long totalSize) {
                    if(currentSize >= totalSize){
                        isImageUploading = false;
                    }else{
                        isImageUploading = true;
                    }
                }
            });
            if(curSelectUploadState == HARDER){
                Glide.with(PersonalSettingsActivity.this).load(photoPath).skipMemoryCache(true).error(R.drawable.register_icon_head_default).into(personImage);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showCropImage(Intent data,final int requestCode) {

        try {
            Bitmap compressPhoto = CompressPhoto.compressBySize(imageStore.getPath(),150,150);

            if (compressPhoto != null) {
                CompressPhoto.saveFile(compressPhoto, imageStore.getPath());
            }
            String tem;
            if(curSelectUploadState == HARDER){
                objectKey = "temp/" + System.currentTimeMillis() + ".jpg";
                tem = objectKey;
            }else{
                objectPhoto  = "temp/" + System.currentTimeMillis() + ".jpg";
                tem = objectPhoto;
            }
            OssUtils.uploadPic(imageStore.getPath(), tem, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {
                    isImageUploading = false;
                }

                @Override
                public void onFailure(PutObjectRequest putObjectRequest, ClientException e, ServiceException e1) {
                    isImageUploading = false;
                    if(curSelectUploadState == HARDER){
                        objectKey = "";
                    }else{
                        objectPhoto = "";
                    }
                    ToastUtils.showToast("头像上传失败！请稍后再试");
                }
            },new OssUtils.onPhotoUploadResult(){
                @Override
                public void onResult(String key, String filePath) {
                    if(requestCode == TAKE_PHOTO_PERSONAL){
                        mapPhoto.put(key, filePath);
                        PersonalPhotoBean bean = new PersonalPhotoBean();
                        bean.photo_add_or_update = 1;
                        bean.view_photo_path = imageStore.getPath();
                        if(listBean.size() == 0){
                            bean.view_id = "initiate_show_img1";
                        }else if(listBean.size() == 1){
                            bean.view_id = "initiate_show_img2";
                        }else if(listBean.size() == 2){
                            bean.view_id = "initiate_show_img3";
                        }else if(listBean.size() == 3){
                            bean.view_id = "initiate_show_img4";
                        }
                        bean.member_phot = key;
                        listBean.add(bean);
                        Message msge = new Message();
                        msge.obj = bean;
                        msge.what = 1;
                        handler.sendMessage(msge);
                    }else if(requestCode == TAKE_PHOTO_UPDATE1){
                        mapPhoto.put(key, filePath);
                        PersonalPhotoBean bean = new PersonalPhotoBean();
                        bean.photo_add_or_update = 1;
                        bean.view_photo_path = imageStore.getPath();
                        bean.view_id = "initiate_show_img1";
                        bean.member_phot = key;
                        listBean.set(0,bean);
                        Message msge = new Message();
                        msge.obj = bean;
                        msge.what = 1;
                        handler.sendMessage(msge);
                    }else if(requestCode == TAKE_PHOTO_UPDATE2){
                        mapPhoto.put(key, filePath);
                        PersonalPhotoBean bean = new PersonalPhotoBean();
                        bean.photo_add_or_update = 1;
                        bean.view_photo_path = imageStore.getPath();
                        bean.view_id = "initiate_show_img2";
                        bean.member_phot = key;
                        listBean.set(1,bean);
                        Message msge = new Message();
                        msge.obj = bean;
                        msge.what = 1;
                        handler.sendMessage(msge);
                    }else if(requestCode == TAKE_PHOTO_UPDATE3){
                        mapPhoto.put(key, filePath);
                        PersonalPhotoBean bean = new PersonalPhotoBean();
                        bean.photo_add_or_update = 1;
                        bean.view_photo_path = imageStore.getPath();
                        bean.view_id = "initiate_show_img3";
                        bean.member_phot = key;
                        listBean.set(2,bean);
                        Message msge = new Message();
                        msge.obj = bean;
                        msge.what = 1;
                        handler.sendMessage(msge);
                    }else if(requestCode == TAKE_PHOTO_UPDATE4){
                        mapPhoto.put(key, filePath);
                        PersonalPhotoBean bean = new PersonalPhotoBean();
                        bean.photo_add_or_update = 1;
                        bean.view_photo_path = imageStore.getPath();
                        bean.view_id = "initiate_show_img4";
                        bean.member_phot = key;
                        listBean.set(3,bean);
                        Message msge = new Message();
                        msge.obj = bean;
                        msge.what = 1;
                        handler.sendMessage(msge);
                    }
                }

                @Override
                public void onProgress(long currentSize, long totalSize) {
                    if(currentSize >= totalSize){
                        isImageUploading = false;
                    }else{
                        isImageUploading = true;
                    }
                }
            });
            if(requestCode == TAKE_PHOTO){
                Glide.with(this).load(imageStore.getPath()).into(personImage);
            }/*else if(requestCode == TAKE_PHOTO_PERSONAL){
                Glide.with(this).load(imageStore.getPath()).into(personImage);
            }else if(requestCode == TAKE_PHOTO_UPDATE1){
                Glide.with(this).load(imageStore.getPath()).into(initiate_show_img1);
            }else if(requestCode == TAKE_PHOTO_UPDATE2){
                Glide.with(this).load(imageStore.getPath()).into(initiate_show_img2);
            }else if(requestCode == TAKE_PHOTO_UPDATE3){
                Glide.with(this).load(imageStore.getPath()).into(initiate_show_img3);
            }else if(requestCode == TAKE_PHOTO_UPDATE4){
                Glide.with(this).load(imageStore.getPath()).into(initiate_show_img4);
            }*/

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void setListener() {
        findViewById(R.id.common_back).setOnClickListener(this);
        findViewById(R.id.common_home_back).setOnClickListener(this);
        personImage.setOnClickListener(this);
        personAddSkill.setOnClickListener(this);
        personSkills.setOnClickListener(this);
        personAge.setOnClickListener(this);
        personCareer.setOnClickListener(this);
        personEdu.setOnClickListener(this);
        personSave.setOnClickListener(this);
        addImageUpload.setOnClickListener(this);
        initiate_show_img1.setOnClickListener(this);
        initiate_show_img2.setOnClickListener(this);
        initiate_show_img3.setOnClickListener(this);
        initiate_show_img4.setOnClickListener(this);

        initiate_show_img1.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                curSelectUploadState = 101;
                uploadPopup(initiate_show_img1);
                return false;
            }
        });

        initiate_show_img2.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                curSelectUploadState = 102;
                uploadPopup(initiate_show_img2);
                return false;
            }
        });

        initiate_show_img3.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                curSelectUploadState = 103;
                uploadPopup(initiate_show_img3);
                return false;
            }
        });

        initiate_show_img4.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                curSelectUploadState = 104;
                uploadPopup(initiate_show_img4);
                return false;
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                ActivityCollector.removeActivity(this);
                break;

            case R.id.common_home_back:
                startActivity(new Intent(PersonalSettingsActivity.this, MainActivity.class));
                ActivityCollector.removeActivity(this);
                break;

            case R.id.person_image:
                if (isImageUploading) {
                    ToastUtils.showToast("上传图片中，请稍后再试");
                    break;
                }
                curSelectUploadState = HARDER;
                headUploadPopup.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                CommonMethod.setWindowAlpha((float) 0.5, getWindow());
                break;

            case R.id.person_add_skill:
                startActivity(new Intent(PersonalSettingsActivity.this, SkillAuthenticateActivity.class));
                break;

            case R.id.person_skills:
                startActivity(new Intent(PersonalSettingsActivity.this, MySkillsActivity.class));
                break;

            case R.id.person_edu:
                eduChoosePopup.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                CommonMethod.setWindowAlpha((float) 0.5, getWindow());
                break;
            case person_age:
                personAge.setSelection(personAge.getText().length());
                break;
            case R.id.person_save:
                if (isImageUploading) {
                    ToastUtils.showToast("上传图片中，请稍后再试");
                    break;
                }
                String msg = judgepersonAge();
                if (TextUtils.equals(msg, "")) {
                    HashMap<String, String> param = new HashMap<>();
                    param.put("member_age", personAge.getText().toString());
                    param.put("member_occupation", personCareer.getText().toString());
                    param.put("member_education", personEduCode);
                    param.put("member_desc", personIntro.getText().toString());
                    param.put("service", "Accompany_Info.updateUserInfo");
                    if (accompany != null && TextUtils.isEmpty(objectKey)) {
                        if (imageKey.contains("?")) {
                            imageKey = "temp" + imageKey.split("temp")[1].split("\\?")[0];
                            param.put("member_avatar", imageKey);
                        } else if (imageKey.contains("temp")) {
                            imageKey = "temp" + imageKey.split("temp")[1];
                            param.put("member_avatar", imageKey);
                        }
                    }else{
                        param.put("member_avatar", objectKey);
                    }
                    Gson gson = new Gson();
                   /* if (mapPhoto.size() > 0) {
                        List<String> array = new ArrayList<String>();
                        for (String key : mapPhoto.keySet()) {
                            array.add(key);
                        }
                        String temp = gson.toJson(array).replace("\"", "").replace("]", "").replace("[", "");
                        LogUtils.e(TAG + temp);
                        param.put("member_photo", gson.toJson(array).replace("\"", "").replace("]", "").replace("[", ""));
                    }*/
                   if(listBean.size() > 0){
                       List<String> array = new ArrayList<>();
                       for(int i = 0 ;i<listBean.size();i++){
                           array.add(listBean.get(i).member_phot);
                       }
                       String temp = gson.toJson(array).replace("\"", "").replace("]", "").replace("[", "");
                       LogUtils.e(TAG + temp);
                       param.put("member_photo", gson.toJson(array).replace("\"", "").replace("]", "").replace("[", ""));
                   }
                    LogUtils.e(TAG + "param = " + param.toString());

                    CommonRequestNetData.getJsonStringData(PersonalSettingsActivity.this, param, true, new CommonRequestNetData.JsonStringCallBack() {
                        @Override
                        public void parseJsonString(String str) {
                            LogUtils.e(TAG + "save str =" + str);
                            ToastUtils.showToast(str);
                            ActivityCollector.removeActivity(PersonalSettingsActivity.this);
                        }
                    });
                } else {
                    ToastUtils.showToast(msg);
                }
                break;

            case R.id.initiate_upload_img:
                if (isImageUploading) {
                    ToastUtils.showToast("上传图片中，请稍后再试");
                    break;
                }
                curSelectUploadState = PHOTO;
                PersonalPhotoBean bean = new PersonalPhotoBean();
                bean.photo_add_or_update = 1;
                uploadPopup(view);
                break;

            case R.id.initiate_show_img1:
                List<String> listUrl1 = new ArrayList<>();
                if(listBean.size() > 0){
                    for(int i = 0;i<listBean.size();i++){
                        listUrl1.add(listBean.get(i).view_photo_path);
                    }
                    showFullScreenPhot(0,listUrl1);
                }

                break;
            case R.id.initiate_show_img2:
                List<String> listUrl2 = new ArrayList<>();
                if(listBean.size() > 1){
                    for(int i = 0;i<listBean.size();i++){
                        listUrl2.add(listBean.get(i).view_photo_path);
                    }
                    showFullScreenPhot(1,listUrl2);
                }
                break;
            case R.id.initiate_show_img3:
                List<String> listUrl3 = new ArrayList<>();
                if(listBean.size() > 2){
                    for(int i = 0;i<listBean.size();i++){
                        listUrl3.add(listBean.get(i).view_photo_path);
                    }
                    showFullScreenPhot(2,listUrl3);
                }
                break;
            case R.id.initiate_show_img4:
                List<String> listUrl4 = new ArrayList<>();
                if(listBean.size() > 3){
                    for(int i = 0;i<listBean.size();i++){
                        listUrl4.add(listBean.get(i).view_photo_path);
                    }
                    showFullScreenPhot(3,listUrl4);
                }
                break;

            default:
                break;
        }
    }

    private String judgepersonAge() {
        /*
         else if (TextUtils.equals(registerBorn.getText().toString(), "请选择出生日期")) {
            return "请选择出生日期";
        }
         */
        if (TextUtils.isEmpty(personAge.getText().toString())) {
            return "请输入年龄";
        } else if (Integer.valueOf(personAge.getText().toString().trim()) < 18) {
            return "设置年龄必须大于18岁";
        } else {
            return "";
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        if (msg.what == 1) {
            PersonalPhotoBean bena = (PersonalPhotoBean)msg.obj;
            update();
        }
        return false;
    }

    private void update() {
        LogUtils.e("listbean size = " + listBean.size());
        if (listBean.size() >= 4) {
            addImageUpload.setVisibility(View.GONE);
        }else{
            addImageUpload.setVisibility(View.VISIBLE);
        }
        for(int i=0;i<listBean.size();i++){
            if(TextUtils.equals(listBean.get(i).view_id,"initiate_show_img1")){
                Glide.with(PersonalSettingsActivity.this).load(listBean.get(i).view_photo_path)
                        .override(80, 80).centerCrop().into(initiate_show_img1);
                initiate_show_img1.setVisibility(View.VISIBLE);
            }else if(TextUtils.equals(listBean.get(i).view_id,"initiate_show_img2")){
                Glide.with(this).load(listBean.get(i).view_photo_path)
                        .override(80, 80).centerCrop().into(initiate_show_img2);
                initiate_show_img2.setVisibility(View.VISIBLE);
            }else if(TextUtils.equals(listBean.get(i).view_id,"initiate_show_img3")){
                Glide.with(this).load(listBean.get(i).view_photo_path)
                        .override(80, 80).centerCrop().into(initiate_show_img3);
                initiate_show_img3.setVisibility(View.VISIBLE);
            }else if(TextUtils.equals(listBean.get(i).view_id,"initiate_show_img4")){
                Glide.with(this).load(listBean.get(i).view_photo_path)
                        .override(80, 80).centerCrop().into(initiate_show_img4);
                initiate_show_img4.setVisibility(View.VISIBLE);
            }
        }
    }
    HeadUploadPopup popup;
    private void uploadPopup(View view){
         popup = new HeadUploadPopup(this, getWindow(), R.style.animBottomInBottomOut,
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popup.dismiss();
                        switch (view.getId()) {
                            case R.id.upload_photo:

                                if (Build.VERSION.SDK_INT >= 23) {
                                    PersonalSettingsActivity.this.onRuntimePermissionRequest(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                                            new PermissionListener() {
                                                @Override
                                                public void onGranted() {
                                                    if(curSelectUploadState == HARDER){
                                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO);
                                                    }else if(curSelectUploadState == PHOTO){
                                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_PERSONAL);
                                                    }else if(curSelectUploadState == 101){
                                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_UPDATE1);
                                                    }else if(curSelectUploadState == 102){
                                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_UPDATE2);
                                                    }else if(curSelectUploadState == 103){
                                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_UPDATE3);
                                                    }else if(curSelectUploadState == 104){
                                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_UPDATE4);
                                                    }
                                                }

                                                @Override
                                                public void onDenied(List<String> deniedPermissions) {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            ToastUtils.showToast("调起摄像头失败！");
                                                        }
                                                    });
                                                }
                                            });
                                } else{
                                    if(curSelectUploadState == HARDER){
                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO);
                                    }else if(curSelectUploadState == PHOTO){
                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_PERSONAL);
                                    }else if(curSelectUploadState == 101){
                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_UPDATE1);
                                    }else if(curSelectUploadState == 102){
                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_UPDATE2);
                                    }else if(curSelectUploadState == 103){
                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_UPDATE3);
                                    }else if(curSelectUploadState == 104){
                                        ImageHandleUtils.takePhoto(PersonalSettingsActivity.this, imageStore, TAKE_PHOTO_UPDATE4);
                                    }
                                }
                                break;
                            case R.id.upload_album:
                                if(curSelectUploadState == PHOTO){
                                    if (listBean.size() >= 4) {
                                        ToastUtils.showToast("最多选择4张");
                                        break;
                                    }
                                    if (isImageUploading) {
                                        ToastUtils.showToast("上传图片中，请稍后再试");
                                        break;
                                    }
                                    getTakePhoto().onPickMultiple(4 - listBean.size());
                                }else if(curSelectUploadState == HARDER){
                                    getTakePhoto().onPickMultiple(1);
                                }else if(curSelectUploadState >= 101 && curSelectUploadState <= 104){
                                    getTakePhoto().onPickMultiple(1);
                                }
                                break;

                            case R.id.upload_cancel:
                                popup.dismiss();
                                break;
                            default:
                                break;
                        }
                    }
                });
        popup.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        CommonMethod.setWindowAlpha((float) 0.5, getWindow());
    }

    SamplePagerAdapter samplePagerAdapter;
    private void showFullScreenPhot(final int pos,List<String> urls){
        if(urls == null ||urls.isEmpty()){
            return;
        }
        samplePagerAdapter = new SamplePagerAdapter(this,urls);
        FullScreenDialog dialog = new FullScreenDialog(this,R.style.FullScreenDialog,R.layout.layout_view_pager,
                new FullScreenDialog.OnContentViewListener(){
                    @Override
                    public void OnSetContentView(View view) {
                        ViewPager viewPager = (ViewPager)view.findViewById(R.id.pager);
                        viewPager.setAdapter(samplePagerAdapter);
                        viewPager.setCurrentItem(pos,true);
                    }
                });

        samplePagerAdapter.setDialog(dialog);
        dialog.show();

    }
}
